package com.xbp.examsystem.service.impl;


import com.xbp.examsystem.properties.MinioProperties;
import com.xbp.examsystem.service.FileUploadService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: xbp
 * description:
 */
@Service
@EnableConfigurationProperties(value = MinioProperties.class)
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) {

        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();

            boolean b = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            if (b) {
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            } else {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }

            String uploadFilename = file.getOriginalFilename();
            String subfix = uploadFilename.substring(uploadFilename.lastIndexOf("."));
            String prefix = UUID.randomUUID().toString().replaceAll("-", "");
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            String newFileName = format + "/" + prefix + subfix;
            InputStream is = file.getInputStream();
            long size = file.getSize();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(newFileName)
                    .stream(is, size, -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+newFileName;
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }
        return null;
    }

}
